<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/18 0018
 * Time: 17:30
 */

namespace app\admin\controller;

use app\admin\logic\Excel;
use app\admin\logic\Invitation as Invitation_log;
use app\admin\logic\Order as order_logic;
use app\admin\model\Order;
use app\admin\logic\Store_log as Store_log;
use app\common\traits\Page;
use think\Request;
use think\Session;
use think\Db;

class Yewu extends Admin
{
    use page;

    /**
     * 手机端首页
     * @return mixed
     */
    public function home(){
        return $this->loadpower('home');
    }

    /**
     * 业务列表
     * @return mixed
     */
    public function olist(){
        ini_set("memory_limit","2048M");
        $order_logic = new order_logic();
        $map = $this->request->param();

        $map_state = session('map_state');
        if(empty($map_state)){
            $map_state['state_k'] = 0;
        }

        $map = array_merge($map,$map_state);
        if (!empty($map['state_k'])) {
            session('map', $map);
        } else {
            session('map', $map);
        }

        $map = session('map');

        $map = $this->queryData($map);

//        dump($map);die();
        $this->assign('form', $map);
        $data = $this->checkData($map);
//        dump($data);die();
        $data['status'] = ['eq', '1'];
        // 校验权限

        $data = $order_logic->power($data);
        $res = $this->pageshow('order', $data, [], $order = 'state,id desc');
        if (!empty($map['shijianduan'])){
            $a = new \app\admin\logic\Order();
            $map['shijianduan'] = $a->time_slot($map['shijianduan']);
            $shijian = explode('-',$map['shijianduan']);
            $shijian1 = array();
            foreach ($shijian as $v){
                $shijian1 [] = explode(':',trim($v));
            }
            foreach ($shijian1 as $k=>$v){
                unset($shijian1[$k][2]);
            }
            foreach ($shijian1 as $k=>$v){
                $shijian1[$k] =implode(':',$shijian1[$k]);
            }
            $map['shijianduan'] = implode('-',$shijian1);
            foreach ($res as $k=>$v){
                if (empty($res[$k]['shijianduan'])){
                    unset($res[$k]);
                }else{
                    $res[$k]['shijianduan']=explode('-',$v['shijianduan']);
                }
            }
            $res = array_values($res);
            $arr =array();
            foreach ($res as $k=>$v){
                foreach ($v['shijianduan'] as $ke=>$va){
                    $arr[$k][$ke] = floor(str_replace(':','',$va));
                }
            }
            $map['shijianduan'] = explode('-',$map['shijianduan']);
//            dump($map['shijianduan']);
            $arrr = array();
            foreach($map['shijianduan'] as $k=>$v){
                $arrr[$k] = floor(str_replace(':','',$v));
            }
            foreach ($arr as $k=>$v){
                    if ($arr[$k][0]<=floor(str_replace(':','',$arrr[0])) || $arr[$k][1]>=floor(str_replace(':','',$arrr[1]))){
                        if (floor(str_replace(':','',$arrr[0]))>=$arr[$k][1] ){
                            unset($res[$k]);
                        }
                    }
                    else{
                        unset($res[$k]);
                    }
            }

            foreach ($res as $k=>$v){
                    $res[$k]['shijianduan']=implode('-',$v['shijianduan']);
            }
        }
        $banji = new \app\admin\logic\Banji();
        foreach ($res as $k=>$v){
            $res[$k]['banji_text'] = $banji->getModel()->where('id', $res[$k]['banji'])->field('banjiname')->find()['banjiname'];
        }
        $this->assign("list", $res);
        $this->getDatas();//获取页面相关数据
        $this->getCountState();//订单状态的数量统计
        return $this->loadpower('olist');
    }


    /**
     * 添加订单
     * @return array
     */
    public function add()
    {
        $order = new order_logic();

        if (request()->isPost()) {
            $map = $this->request->post();
            if (array_key_exists('shijianduan',$map)){
            }else{

                $map['shijianduan'] = $map['shijianduan1'].'-'.$map['shijianduan2'];
                unset($map['shijianduan1']);
                unset($map['shijianduan2']);
            }
            $data = $this->Verification($map);
            return $order->add($data, $khd = 1);//成功返回1
        } else {
            $this->getDatas();//获取页面相关数据
            $userinfo= session('admin_user');
            $this->assign('depar', $userinfo['depar_id']);
            $this->assign('user_id', $userinfo['adminid']);
            return  $this->loadpower('add');
        }
    }

    /**
     * 查看/修改订单
     * @return array|mixed
     */
    public function edit()
    {
        $order = new order_logic();
        // 修改数据
        if ($this->request->isPost()) {
            $map = $this->request->post();
            if (array_key_exists('shijianduan',$map)){
            }else{

                $map['shijianduan'] = $map['shijianduan1'].'-'.$map['shijianduan2'];
                unset($map['shijianduan1']);
                unset($map['shijianduan2']);
            }

            $data = $this->Verification($map);

            return $order->updata($data);
        } else { // 查看数据
            $id = $this->request->param('id');
            $map['id'] = $id;
            $map['status'] = 1;
            $res = $order->find($map);
            $userinfo= session('admin_user');
//            if($userinfo['adminid'] == 1){
//                $order->sendSms();
//            }
//            dump($data);
            $this->getDatas();//获取页面相关数据
            if (empty($res['shijianduan'])){
                $res['shijianduan1'] = '';
                $res['shijianduan2'] = '';
            }else{
                $res['shijianduan1'] = explode('-',$res['shijianduan'])[0];
                $res['shijianduan2'] = explode('-',$res['shijianduan'])[1];
            }
            $this->assign('data', $res);
            $this->logSelect($id);                      // 查看邀约记录
            $this->selectStore($id);                    // 查看到店记录
            $logdata = $this->getCommonModel()->getOrderLogById($id);
            $this->assign('logdata', $logdata);
            return $this->loadpower('edit');
        }
    }

    /**
     * 删除订单
     * @return array
     */
    public function del()
    {
        $isPost = $this->request->isPost();
        if ($isPost) {
            $id = $this->request->param('id');
            $order = new Order_logic();
            $data['id'] = $id;
            $data['status'] = 0;
            $res = $order->del($data);
            if ($res) {
                return ['status' => '1', 'msg' => '数据删除成功！'];
            } else {
                return ['status' => '0', 'msg' => '数据删除失败！'];
            }
        }
    }

    /**
     * 新增订单排重联系方式（手机号/微信/QQ）
     * @return \think\response\Json
     */
    public function getContact()
    {
        $value = trim($this->request->param('value'));
        $name = $this->request->param('name');
        $id = $this->request->param('id');
        if (!empty($value)) {
            $order = new order_logic();
            $data[$name] = $value;
            $data['status'] = 1;
            $res = $order->ContactFind($data);
        }
        if (!empty($res) && $res['id'] != $id) {
            $valid['name'] = $name;
            $valid['value'] = $value;
            if(!empty($id)){
                $valid['id'] = $id;
            }
            session('valid',$valid);
            if (strpos(' '.$name, 'qq')) {
                return JSON(['valid' => false]);
            }
            if (strpos(' '.$name, 'phone')) {
                return JSON(['valid' => false]);
            }
            if (strpos(' '.$name, 'wechat')) {
                return JSON(['valid' => false]);
            }
        } else {
            return JSON(['valid' => true]);
        }
    }

    /**
     * 显示重复的客资订单
     * @return mixed
     */
    public function ValidatorInfo(){
        $valid = session('valid');
        if (!empty($valid)) {
            $data[$valid['name']]=$valid['value'];
            $data['status'] = 1;
            if(!empty($valid['id'])){
                $data['id'] = ['neq',$valid['id']];
            }
            $res = $this->pageshow('order', $data, [], $order = 'state,id desc');
            if(!empty($valid['id'])) {
                $res = collect($res)->whereNotIn('id', $valid['id'])->all();
            }
            $this->assign('value',$valid['value']);
            $this->assign("list", $res);
            return $this->fetch('validator-info');
        }
    }

    /**
     * 保存邀约日志
     * @return array
     */
    public function logSave()
    {
        $invitation_log = new Invitation_log();
        $order = new order_logic();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $map = $this->Verification($data);
            $map['yytime'] = time();
            $res = $order->updata($map);
            if ($res) {
                $maps = $this->invitCheck($map);
                $maps['time'] = time();
                $user = session('admin_user');
                $maps['personnel'] = $user['adminid'];
                $result = $invitation_log->logSaves($maps);
                if ($result) {
                    return ['status' => '1', 'info' => '数据更新成功！'];
                } else {
                    return ['status' => '0', 'info' => '数据更新成功！'];
                }
            } else {
                return ['status' => '0', 'info' => '数据添加失败！'];
            }
        }
    }

    /**
     * 查看邀约日志
     * @param $id
     */
    public function logSelect($id)
    {
        $invitation_log = new Invitation_log();
        $data['order_id'] = ['eq', $id];
        $res = $invitation_log->logSelects($data);
        $this->assign('logs', $res);
    }

    /**
     * 保存门店服务记录
     * @return array
     */
    public function saveStore()
    {
        $store = new Store_log();
        $order = new order_logic();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $map = $this->Verification($data);
            $res = $order->updata($map);
            if ($res) {
                $maps = $this->storeCheck($map);
                $maps['time'] = time();
                $user = session('admin_user');
                $maps['operator'] = $user['adminid'];
                $result = $store->saveStroe($maps);
                if ($result) {
                    return ['status' => '1', 'info' => '数据更新成功！'];
                } else {
                    return ['status' => '1', 'info' => '数据更新成功！'];
                }
            } else {
                return ['status' => '0', 'info' => '数据更新失败！'];
            }
        }
    }

    /**
     * 查看门市服务记录
     * @param $id
     */
    public function selectStore($id)
    {
        $store = new Store_log();
        $data['order_id'] = ['eq', $id];
        $res = $store->selectStore($data);
        $this->assign('store_log', $res);
    }

    /**
     * 快捷查询
     * @return mixed
     */
    public function stateIsMap(){
        $state = $this->request->param();
        $map['state_k'] = $state['state_k'];
        session('map_state', $map);
        $data['url'] = url('olist');
        return $data;
    }

    /**
     * 分配订单
     * @return array|mixed
     */
    public function allot()
    {
        $order = new order_logic();
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $map = $this->Verification($data);
            $map['state'] = 2;
            return $order->updata($map);
        } else {
            $id = $this->request->param('id');
            $this->allotFind($id);
            $map['id'] = $id;
            $map['status'] = 1;
            $res = $order->find($map);
            $this->getDatas();
            $this->assign('data', $res);
            return $this->fetch();
        }
    }

    /**
     * 批量分配
     * @return mixed
     * @author: Guo
     */
    public function batchall()
    {
        $map = $this->request->param();
        $idarray = $map['id'];
        $order = new order_logic();
        foreach ($idarray as &$v) {
            $data['id'] = $v;
            $data['state'] = 2;
            $data['yykf'] = $map['invitation'];
            $data['yykf_group'] = $map['invitation_group'];
            $res = $order->updata($data);
        }
        return $res;
    }


    /**
     * 批量分配查询
     * @return mixed
     * @author: Guo
     */
    public function batch()
    {
        $map = $this->request->param();

        if (!empty($map['editid'])) {
            $map = session('batchmap');
            session('batchmap', $map);
        } else {
            session('batchmap', $map);
        }
        $map = session('batchmap');
        $this->assign('form', $map);
        $data = $this->checkData($map);
        $data['status'] = ['eq', '1'];
        $data['state'] = ['eq', '1'];
        //  $data['invitation'] = ['eq', ''];
        $order = new order_logic();
        // 校验权限
        $data = $order->power($data);
        $res = $this->pageshow('order', $data);
        $this->assign("list", $res);
        $this->getDatas();
        return $this->fetch('distr');
    }


    /**
     * 分配客资权限检测
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     * @author: Guo
     */
    public function allotFind($id)
    {
        $order = new order_logic();
        $olddata = ($order->getModel())::get($id);
        $user = session('admin_user.adminid');
        if ($olddata['state'] == 1) {
            if ($this->hasRole(['yyjl']) || $this->hasRole(['yyzg'])) {//邀约经理 权限
                return ['msg' => "恭喜您有权限访问！", 'status' => "1", "url" => url('allot', ['id' => $id]), 'icon' => 1];
            } elseif ($this->hasRole(['yyzy'])) {
                if ($olddata['invitation'] != $user) {
                    return ['msg' => "订单已分配，您需要通过主管重新分配！", 'status' => "0", 'icon' => 4];
                }
            }
            return ['msg' => "您没有权限访问！", 'status' => "0", "url" => url('allot', ['id' => $id])];
        }
        return ['msg' => "顾客已进入下一服务流程您没有权限修改！", 'status' => "0"];
    }

}